//
//  APR_LogManager.swift
//  EddidOne
//
//  Created by chenfanfang on 2021/6/13.
//  Copyright © 2021 IMac . All rights reserved.
//

import UIKit
import CocoaLumberjack
import SSZipArchive

private let LogManager_Queue = DispatchQueue(label: "LogManager_Queue")

/// 日志的类型
enum APR_LogType: String {
    /// token相关
    case token
    /// 登录结果
    case loginResult
    /// 请求
    case request
    /// 响应成功
    case response
    /// 响应失败【比如连不上服务器，断网】
    case responseError
    /// 通话方面的日志
    case call
    /// 自定义的消息类型
    case customMesssage
    /// 用户信息相关
    case userInfo
    /// app的生命周期
    case appLifeCycle
    /// 支付相关
    case purchase
    /// 公共日志【不在以上的日志统一称为公共日志】
    case publicLog
}

struct APR_LogMessage {
    let key: APR_LogMessageKey
    let value: String
}

/// 日志信息的key
enum APR_LogMessageKey {
    //=======================
    //       public
    //=======================
    /// 数据
    case data
    /// 参数
    case params
    /// 错误
    case error
    /// 消息
    case message
    /// 事件ID
    case actionID
    /// 发起的事件
    case action
    /// 点击的事件
    case clickAction
    /// 事件的响应
    case actionResponse
    /// 接收到数据【比如接收到腾讯IM内部发出的一些状态的变化】
    case receive
    case loginResult
    //=======================
    //     request/response
    //=======================
    /// 请求头
    case header
    /// 请求ID
    case requestId
    /// 接口
    case api
    /// 耗时
    case spendTime
    //=======================
    //       public
    //=======================
    case token
    
}

/// 日志工具
class APR_LogManager: NSObject {
    private static let fileLogger: DDFileLogger = {
        /**
         NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
         NSString *baseDir = paths.firstObject;
         NSString *logsDirectory = [baseDir stringByAppendingPathComponent:@"Logs"];
         */
        var path: String?
        if let tempPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
            path = tempPath.appendingPathComponent("chenfanfang_Logs")
        }
        let logFileManager: DDLogFileManagerDefault = .init(logsDirectory: path)
        let fileLogger = DDFileLogger.init(logFileManager: logFileManager)
        fileLogger.logFileManager.maximumNumberOfLogFiles = 5
        fileLogger.maximumFileSize = 1024 * 1024 * 10 // 每个日志文件10M
        fileLogger.rollingFrequency = -1
        fileLogger.logFileManager.logFilesDiskQuota = 0
        /**
         _dateFormatter = [[NSDateFormatter alloc] init];
         [_dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4]; // 10.4+ style
         [_dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
         [_dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8 * 60 * 60]];
         [_dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm:ss:SSS"];
         */
        let formatter = DateFormatter()
        formatter.formatterBehavior = .behavior10_4
        formatter.timeZone = TimeZone(secondsFromGMT: 8 * 60 * 60)
        formatter.dateFormat = "yyyy/MM/dd HH:mm:ss:SSS"
        fileLogger.logFormatter = DDLogFileFormatterDefault.init(dateFormatter: formatter)
        return fileLogger
    }()
    /// 初始化日志工具
    static func setup() {
        LogManager_Queue.async {
            DDLog.add(fileLogger)
            print("\n\n\n日志位置\n\n\n\(fileLogger.logFileManager.logsDirectory)\n\n\n")
        }
    }
    /// 添加日志
    /// - Parameters:
    ///   - logType: 日志类型
    ///   - messages: 日志信息数组
    static func addLog(logType: APR_LogType, messages: [APR_LogMessage]) {
        LogManager_Queue.async {
            var log: String = "[\(logType.rawValue)] ---> "
            for message: APR_LogMessage in messages {
                let itemLog = "\(message.key) : \(message.value)       "
                log += itemLog
            }
            DDLogInfo(log)
        }
    }
    static func uploadLogFile() {
        guard let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first else {
            return
        }
        var zipPath = documentPath
        if zipPath.hasSuffix("/") == false {
            zipPath += "/"
        }
        zipPath += "chenfanfang_logs.zip"
        let allLogPaths: [String] = fileLogger.logFileManager.unsortedLogFilePaths
        print("开始上传日志")
        LogManager_Queue.async {
            if SSZipArchive.createZipFile(atPath: zipPath, withFilesAtPaths: allLogPaths) {
                let url = URL(fileURLWithPath: zipPath)
                let data = try? Data(contentsOf: url)
                if data == nil {
                    return
                }
//                APR_PublicApiTool.func_uploadFile(fileData: data!, success: { (resultModel: APR_FileUploadResultModel) in
//                    print("上传日志成功")
//                }, failure: { (message: String?) in
//                    print("上传日志失败: \(message ?? "")")
//                })
            } else {
                print("压缩失败")
            }
        }
    }
}
